package com.zkx.mvp.api;

import com.zkx.mvp.api.support.CustomGsonConverterFactory;
import com.zkx.mvp.api.support.HttpClient;
import com.zkx.mvp.model.SessionRequest;
import com.zkx.mvp.model.SessionResult;
import com.zkx.mvp.model.test.TestRequest;
import com.zkx.mvp.model.test.TestResponse;
import com.zkx.mvp.persenter.support.HttpResultFunc;
import com.zkx.mvp.persenter.support.HttpResultFuncList;

import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.Observable;

/**
 * Author：zhangkx on 2017/6/16 16:22
 * Email：zkx9025@163.com
 */

public class HttpApi {
    public static HttpApi instance;
    private HttpApiService service;

    private HttpApi(OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.API_BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 添加Rx适配器
                .addConverterFactory(CustomGsonConverterFactory.create()) // 添加Gson转换器
                .client(okHttpClient)
                .build();
        service = retrofit.create(HttpApiService.class);
    }
    public static HttpApi getInstance() {
        if (instance == null) {
            instance = new HttpApi(new HttpClient().provideOkHttpClient());
        }
        return instance;
    }

    public Observable<List<SessionResult>> getSession(){
        SessionRequest session = new SessionRequest();
        session.setChannel("xinfushe");
        session.setCode("fwrewrewrr32");
        session.setIsFirst("1");
        session.setSource("2");
        return service.getSession(session).map(new HttpResultFuncList<SessionResult>());
    }

    /**
     * 获取天气的api
     * @param city 查询城市
     * @return
     */
    public Observable<TestResponse> getWeather(String city){
        TestRequest testRequest = new TestRequest();
        testRequest.setCity(city);
        testRequest.setAppkey(Constant.TEST_WEATHER_APP_KEY);
        return service.getWeather(testRequest).map(new HttpResultFunc<TestResponse>());
    }
}
